package com.kitchen.service;

import com.kitchen.dao.ChefDAO;
import com.kitchen.dao.DishDAO;
import com.kitchen.dao.OrderDAO;
import com.kitchen.entity.*;
import com.kitchen.exception.OrderException;
import com.kitchen.util.FileUtil;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单服务类
 * 体现业务逻辑处理，使用Map和Set集合
 */
public class OrderService {
    private OrderDAO orderDAO;
    private DishDAO dishDAO;
    private ChefDAO chefDAO;
    
    public OrderService() {
        this.orderDAO = new OrderDAO();
        this.dishDAO = new DishDAO();
        this.chefDAO = new ChefDAO();
    }
    
    /**
     * 创建订单
     */
    public Order createOrder(String tableNumber, Map<Integer, Integer> dishMap) {
        // 验证菜品
        for (Integer dishId : dishMap.keySet()) {
            Dish dish = dishDAO.findById(dishId);
            if (dish == null) {
                throw new OrderException("菜品不存在，ID: " + dishId);
            }
            if (!"可用".equals(dish.getStatus())) {
                throw new OrderException("菜品不可用: " + dish.getDishName());
            }
        }
        
        // 生成订单号
        String orderNumber = generateOrderNumber();
        
        // 创建订单对象
        Order order = new Order(orderNumber, tableNumber);
        
        // 添加订单明细
        List<OrderItem> items = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : dishMap.entrySet()) {
            Dish dish = dishDAO.findById(entry.getKey());
            OrderItem item = new OrderItem(entry.getKey(), entry.getValue(), dish.getPrice());
            item.setDishName(dish.getDishName());
            items.add(item);
        }
        order.setItems(items);
        order.calculateTotalAmount();
        
        // 保存订单
        Integer orderId = orderDAO.createOrder(order);
        if (orderId != null) {
            order.setOrderId(orderId);
            FileUtil.writeLog("创建订单成功: " + orderNumber + ", 桌号: " + tableNumber);
            return order;
        } else {
            throw new OrderException("创建订单失败");
        }
    }
    
    /**
     * 查询所有订单
     */
    public List<Order> getAllOrders() {
        return orderDAO.findAll();
    }
    
    /**
     * 根据状态查询订单
     */
    public List<Order> getOrdersByStatus(String status) {
        return orderDAO.findByStatus(status);
    }
    
    /**
     * 分配厨师到订单
     */
    public boolean assignChefToOrder(Integer orderId, Integer chefId) {
        Order order = orderDAO.findById(orderId);
        if (order == null) {
            throw new OrderException("订单不存在");
        }
        
        Chef chef = chefDAO.findById(chefId);
        if (chef == null) {
            throw new OrderException("厨师不存在");
        }
        
        if (!"空闲".equals(chef.getStatus())) {
            throw new OrderException("厨师当前忙碌，无法分配");
        }
        
        boolean success = orderDAO.assignChef(orderId, chefId);
        if (success) {
            chefDAO.updateStatus(chefId, "忙碌");
            FileUtil.writeLog("分配厨师成功: 订单ID=" + orderId + ", 厨师ID=" + chefId);
        }
        return success;
    }
    
    /**
     * 完成订单
     */
    public boolean completeOrder(Integer orderId) {
        Order order = orderDAO.findById(orderId);
        if (order == null) {
            throw new OrderException("订单不存在");
        }
        
        boolean success = orderDAO.completeOrder(orderId);
        if (success && order.getChefId() != null) {
            chefDAO.updateStatus(order.getChefId(), "空闲");
            FileUtil.writeLog("订单完成: 订单ID=" + orderId);
        }
        return success;
    }
    
    /**
     * 按类型统计菜品销量 - 使用Map集合
     */
    public Map<String, Integer> getDishStatisticsByType() {
        List<Order> orders = orderDAO.findAll();
        Map<String, Integer> statistics = new HashMap<>();
        
        for (Order order : orders) {
            if ("已完成".equals(order.getStatus())) {
                for (OrderItem item : order.getItems()) {
                    Dish dish = dishDAO.findById(item.getDishId());
                    if (dish != null) {
                        String type = dish.getDishType();
                        statistics.put(type, statistics.getOrDefault(type, 0) + item.getQuantity());
                    }
                }
            }
        }
        
        return statistics;
    }
    
    /**
     * 获取最受欢迎的菜品 - 使用Map和排序
     */
    public List<Map.Entry<String, Integer>> getPopularDishes(int topN) {
        List<Order> orders = orderDAO.findAll();
        Map<String, Integer> dishCount = new HashMap<>();
        
        for (Order order : orders) {
            if ("已完成".equals(order.getStatus())) {
                for (OrderItem item : order.getItems()) {
                    String dishName = item.getDishName();
                    dishCount.put(dishName, dishCount.getOrDefault(dishName, 0) + item.getQuantity());
                }
            }
        }
        
        return dishCount.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .limit(topN)
                .collect(Collectors.toList());
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNumber() {
        return "ORD" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + 
               String.format("%04d", new Random().nextInt(10000));
    }
}

